package com.baosight.xcyber.tm.re.controller;

import com.alibaba.fastjson.JSONObject;
import com.baosight.xcyber.tm.re.domain.UIApplicationInfo;
import com.baosight.xcyber.tm.re.domain.UITreeNode;
import com.baosight.xcyber.tm.re.repository.ApplicationRepository;
import com.zeroc.IceGrid.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping({"/ui"})
public class UIController {

    public static Logger logger = LoggerFactory.getLogger(UIController.class);

    @Autowired
    private ApplicationRepository applicationRepository;

    @Autowired
    private AdminSessionPrx adminSessionPrx;

    private AdminPrx adminPrx=null;

    @PostMapping("/getApplication")
    public List<UITreeNode> getApplication(){
        return  applicationRepository.getUiApplicationInfoList();
    }

    @PostMapping("/startServer")
    public JSONObject startServer(@RequestBody JSONObject jsonObject){
        try {
            String serverName=jsonObject.getString("serverName");
            getAdminPrx().startServer(serverName);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return getJSONFailed();
        }
        return getJSONSUccess();
    }
    @PostMapping("/stopServer")
    public JSONObject stopServer(@RequestBody JSONObject jsonObject){
        try {
            String serverName=jsonObject.getString("serverName");
            getAdminPrx().stopServer(serverName);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return getJSONFailed();
        }
        return getJSONFailed();
    }

    private JSONObject getJSONSUccess(){
        return new JSONObject(){{
            put("status","200");
            put("message","success");
        }};
    }
    private JSONObject getJSONFailed(){
        return new JSONObject(){{
            put("status","500");
            put("message","failed");
        }};
    }

    private AdminPrx getAdminPrx(){
        if(this.adminPrx==null){
            synchronized (this){
                if(this.adminPrx==null){
                    this.adminPrx=adminSessionPrx.getAdmin();
                }
            }
        }
        return this.adminPrx;
    }
}
